from ssd1306 import SSD1306_I2C
from machine import Pin,I2C,ADC,PWM
import time
import random
#  
# i2c=I2C(0,scl=Pin(5),sda=Pin(4))
# oled=SSD1306_I2C(i2c)
#  
 
from machine import Pin, I2C
from lib.sh1106 import SH1106, SH1106_I2C
import utime
from setting import *
 
i2c = I2C(scl=Pin(POWER_PIN_OLED_I2C_SCL), sda=Pin(POWER_PIN_OLED_I2C_SDA), freq=500000)
oled = SH1106_I2C(128, 64, i2c, None, 0x3c)

pos_buzzer = PWM(Pin(POWER_PIN_SOURND_NO_SOURCE, Pin.OUT))

# ps1_button = Pin(POWER_PIN_PS1_Z, Pin.IN)
ps2x = ADC(Pin(POWER_PIN_PS1_X), atten=ADC.ATTN_11DB)
# ps1_y = ADC(Pin(POWER_PIN_PS1_Y), atten=ADC.ATTN_11DB)
# ps2x=ADC(Pin(2))
# ps2x.atten(ADC.ATTN_11DB)
#生命值的绘制
live_list=[0x30,0x4C,0x42,0x21,0x21,0x42,0x4C,0x30]
#绘制恐龙
dinosaur=[0x03,0x01,0x00,0x00,0x00,0x00,0x01,0x03,0x07,0x7F,0xFF,0x8F,0xAF,0x8D,0xF9,0x78,
0xC0,0xE0,0xF0,0x78,0x7F,0xFD,0xF0,0xFC,0xFF,0xF9,0xF0,0xE0,0xC0,0x00,0x80,0x00]
#初始化屏幕
oled.fill(0)
oled.p8(live_list,0,0)
oled.p8(live_list,9,0)
oled.p8(live_list,18,0)
oled.text('0',120,0)
oled.p16(dinosaur,0,48)
oled.rect(117,53,10,10,True)
oled.show()
#设定游戏参数，一次跳跃用12帧数据处理
jump = 0
jump_num = [48,34,23,15,10,8]#根据恐龙的跳跃位置和自由落体运动规律得到的每帧绘制恐龙的位置
fall = False#降落标志
score = 0#分数
x = 0
live=3#生命值为3
#障碍物随机坐标
box1 = random.randint(40,120)
box2 = random.randint(40,120) + box1
speed = 3#初始游戏速度
pos_buzzer.duty(0)

while True:
    #如果还有生命值
    if live:
        #当摇杆推动且恐龙在地平线上才触发跳动
        if ps2x.read()>2500 and jump == 0:
            pos_buzzer.duty(900)
            pos_buzzer.freq(495)
#             time.sleep_ms(500)
#             pos_buzzer.freq(294)
            jump = 1
        #一直升高直到最高点
        if jump != 0:
            jump += 1 if not fall else -1
            #降落到地面
            if jump == 0:
                pos_buzzer.duty(0)
                fall = False
                score += 1
        if jump == 5:
            fall = True#跳到最高点下落
        
        x += speed
        speed = 3 + score//10#速度随积分增加
        #刷新屏幕
        oled.fill(0)
        #显示血量值
        for i in range(live):
            oled.p8(live_list,i*9,0)
        #更新分数
        oled.text(str(score),120,0)
        #画小恐龙的外形
        oled.p16(dinosaur,0,jump_num[jump])
        #画障碍物
        oled.rect(box1-x,55,4,8,True)
        oled.rect(box2-x,55,4,8,True)
        #判断当前障碍物过了屏幕，就把它变最后一个
        if box1+4-x <= 0:
            box1 = box2 
            box2 = box1 + random.randint(40,120)
        #判断是否碰到障碍物
        if 15 > box1-x > 12 and 48-jump_num[jump] < 14:
            live-=1
            score-=1
            time.sleep_ms(20)
        elif 0<=box1-x<4 and 48-jump_num[jump] < 14:
            live-=1
    #生命值为0，恐龙挂掉了
    else:
        oled.text('GAME_OVER',29,30)
    oled.show()